﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Threading;
using System.Web.Script.Serialization;
using System.Web;
using System.Diagnostics;

namespace Comet
{
    public partial class Main : Form
    {

        BackgroundWorker main = new BackgroundWorker();
        BackgroundWorker socketListener = new BackgroundWorker();
        System.Windows.Forms.Timer DisplayUpdator = new System.Windows.Forms.Timer();

        Communications communications;
        ChatHandler chatHandler;
        string Title;
        PerformanceCounter memoryCounter;
        

        public Main()
        {
            System.Threading.ThreadPool.SetMaxThreads(400, 250);
            System.Threading.ThreadPool.SetMinThreads(100, 50);

            communications = new Communications();
            chatHandler = new ChatHandler();

            InitializeComponent();
            Icon = Comet.Properties.Resources.hugeicon;
            Title = Text;

            memoryCounter = new PerformanceCounter("Process", "Working Set - Private", Process.GetCurrentProcess().ProcessName);

            socketListener.DoWork += new DoWorkEventHandler(socketListener_DoWork);
            socketListener.RunWorkerAsync();

            DisplayUpdator.Tick += new EventHandler(DisplayUpdator_Tick);
            DisplayUpdator.Interval = 1500;
            DisplayUpdator.Start();

            Extra.ReLoadBanStuff();
        }

        void DisplayUpdator_Tick(object sender, EventArgs e)
        {
            labelOnlineChats.Text = Stats.ChatStats.OnlineChats.ToString();
            labelOnlineAnyones.Text = Stats.ChatStats.OnlineAnyones.ToString();
            labelOnlineMalesFemales.Text = Stats.ChatStats.OnlineMalesToFemales.ToString();
            labelOnlineMalesMales.Text = Stats.ChatStats.OnlineMalesToMales.ToString();
            labelOnlineFemalesMales.Text = Stats.ChatStats.OnlineFemalesToMales.ToString();
            labelOnlineFemalesFemales.Text = Stats.ChatStats.OnlineFemalesToFemales.ToString();

            labelAllChats.Text = Stats.ChatStats.AllChats.ToString();
            labelAllAnyones.Text = Stats.ChatStats.AllAnyones.ToString();
            labelAllMalesFemales.Text = Stats.ChatStats.AllMalesToFemales.ToString();
            labelAllMalesMales.Text = Stats.ChatStats.AllMalesToMales.ToString();
            labelAllFemalesMales.Text = Stats.ChatStats.AllFemalesToMales.ToString();
            labelAllFemalesFemales.Text = Stats.ChatStats.AllFemalesToFemales.ToString();

            labelMessagesSent.Text = Stats.ChatStats.MessagesSent.ToString();
            labelBandwidth.Text = (Stats.ChatStats.OutboundData / 1024).ToString();

            Text = Title + " - " + string.Format("{0}M", memoryCounter.RawValue / 1024 / 1024);
        }


        void socketListener_DoWork(object sender, DoWorkEventArgs e)
        {
            HttpListener listener = new HttpListener();
            listener.Prefixes.Add("http://*:80/");
            listener.Start();

            while (true)
            {
                while (true)
                    try
                    {
                        HttpListenerContext request = listener.GetContext();
                        ThreadPool.QueueUserWorkItem(handleRequest, request);
                    }
                    catch (HttpListenerException) { break; }
                    catch (InvalidOperationException) { break; }
            }
        }

        void handleRequest(object contextObj)
        {
            HttpListenerContext context = (HttpListenerContext)contextObj;

            string[] requestString = context.Request.RawUrl.Replace("/", "").Split('?');
            string requestFile = requestString[0];
            string requestParams = requestString.Length > 1 ? requestString[1] : null;
            context.Response.KeepAlive = false;
            if (chatHandler.chatHandlerMethods.Contains(requestFile)) chatHandler.HandleMethod(requestFile, context);
            else if (requestFile == "verify") Verify.Handle(context, requestParams);
            else if (requestFile == "upload") Imgur.Handle(context);
            else if (requestFile == "reset")
            {
                Communications.LoadWebFiles();
                Extra.ReLoadBanStuff();
                Communications.SendResponse(context, Communications.DataType.Text, "reset complete");
            }
            else communications.serveWebFile(requestFile, context, requestParams);

            try
            {
                context.Request.InputStream.Close();
            }
            catch { }
        }

        private void buttonRestart_Click(object sender, EventArgs e)
        {
            Application.Restart();
        }

        private void buttonReload_Click(object sender, EventArgs e)
        {
            Communications.LoadWebFiles();
            Extra.ReLoadBanStuff();
        }

    }
}